/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.telsoft.managedbean.function;

import com.telsoft.business.LibraryBusiness;
import com.telsoft.entity.LibraryEntity;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author THANHBINH
 */
@ManagedBean(name = "func_download")
@ViewScoped
public class Func_Download implements Serializable {

    private Func_downloadleft downloadleft;
    private LibraryEntity lib;

    public Func_Download() {
        FacesContext context = FacesContext.getCurrentInstance();
        downloadleft = (Func_downloadleft) context.getApplication().evaluateExpressionGet(context, "#{func_downloadleft}", Func_downloadleft.class);
        lib = downloadleft.getLib();
    }

    public void download() throws IOException {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
        response.reset();
        response.setContentType("application/force-download");
        String downloadFile;
//      downloadFile=leftProcess.getLib().get(0).getLibID();
        downloadFile = LibraryBusiness.getFileFromFileID(downloadleft.getLib().getLibID());
        response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadleft.getLib().getName() + "\"");
        BufferedInputStream input = null;
        BufferedOutputStream output = null;
        File file = null;

        try {
            file = new File(downloadFile);
            input = new BufferedInputStream(new FileInputStream(file));
            output = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[10240];
            for (int length; (length = input.read(buffer)) > 0;) {
                output.write(buffer, 0, length);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            output.close();
            input.close();
            file.delete();
        }
        facesContext.responseComplete();
    }

    public LibraryEntity getLib() {
        return lib;
    }

    public void setLib(LibraryEntity lib) {
        this.lib = lib;
    }
    
}
